package com.linden.std.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linden.std.domain.po.SysMenu;
import com.linden.std.domain.po.SysRole;
import com.linden.std.domain.po.SysUser;
import com.linden.std.mapper.SysUserMapper;
import com.linden.std.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author linden
 * @since 2025-09-20
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public SysUser getUserByUsername(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username)
               .eq(SysUser::getDelFlag, 0);
        return getOne(wrapper);
    }

    @Override
    public boolean existsByUsername(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username)
               .eq(SysUser::getDelFlag, 0);
        return count(wrapper) > 0;
    }

    @Override
    public List<String> obtainUserRoleAndPermissions(Long userId) {
        return baseMapper.selectUserPermissions(userId);
    }

    @Override
    public void updateLastLoginInfo(Long userId, String loginIp) {
        SysUser user = new SysUser();
        user.setId(userId);
        user.setLastLoginTime(LocalDateTime.now());
        user.setLastLoginIp(loginIp);
        updateById(user);
    }

    @Override
    public List<SysRole> getUserRoles(Long userId) {
        return baseMapper.selectUserRoles(userId);
    }

    @Override
    public List<SysMenu> getUserMenus(Long userId) {
        return baseMapper.selectUserMenus(userId);
    }
}
